package com.qianbei.common.base;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qianbei.R;
import com.qianbei.common.LoadMoreListView;
import com.qianbei.common.adapter.CommonAdapter;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.ProgressView;

import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by gml on 16/7/6.
 */
public abstract class BaseListViewFragment<T> extends BaseFragment implements LoadMoreListView.OnLoadMoreListViewListener {


    protected LoadMoreListView mLoadMoreListView;
    private CommonAdapter mListViewAdapter;
    private ProgressView mProgressView;
    //    private View mNoDataView;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    // 下一页显示页码，小于零则表示没有更多数据了
    // 下拉刷新
    protected int mPage = 1;


    public boolean isInit;//是否初始化完成
    public boolean isVisible;//是否可见


    /**
     * 是否第一次加载
     */
    private boolean isFirstLoad = true;


    private boolean isCanResh = true;//设置 是否可以 下拉刷新

    public boolean isCanResh() {
        return isCanResh;
    }

    public void setCanResh(boolean canResh) {
        isCanResh = canResh;
    }


    View view;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("kh", "onCreateView-------------:");

        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
            return view;
        }
        view = inflater.inflate(R.layout.comm_listview_activity, container, false);


//        mNoDataView = v.findViewById(R.id.colect_nodata);
//        mNoDataView.findViewById(R.id.collect_nodata_go).setOnClickListener(
//                this);


        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d("kh", "onViewCreated-------------:");
        View v = getView();
        mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);

        mSwipeRefreshLayout.setEnabled(isCanResh);
        mSwipeRefreshLayout.setColorSchemeColors(Color.parseColor("#1e81d2"));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPage = 1;
                requestData(false);
            }
        });

        mProgressView = (ProgressView) v.findViewById(R.id.progress);
        mLoadMoreListView = (LoadMoreListView) v.findViewById(R.id.collect_list_view);
        mLoadMoreListView.setOnLoadMoreListViewListener(this);
        mListViewAdapter = setAdapter();//new Home_user_Adapter(this);
        mLoadMoreListView.setAdapter(mListViewAdapter);

        isInit = true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("kh", "setUserVisibleHint:" + isVisibleToUser);
        isVisible = isVisibleToUser;
        lazyLoad();
    }

    public void lazyLoad() {

        Log.d("kh", "lazyLoad-------------isInit:" + isInit + " isVisible:" + isVisible);
        if (isInit && isVisible) {

            if (isFirstLoad) {
                isFirstLoad = false;
                mPage = 1;
                requestData(true); //请求数据 接口
            }

        }
    }


    /**
     * 请求 数据接口交给 子类处理
     *
     * @param isFirst
     */


    public void requestData(boolean isFirst) {
        ServerControl sc = setServerControl();
//                new ServerControl(Request.Method.GET,url + "page" + "=" + mPage + "&");
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {

                    ArrayList<T> list = setList(sr.bodyData);
//                            (ArrayList) JSON.parseArray(
//                            sr.bodyData.optJSONArray("collection_masters")
//                                    .toString(), Home_buttonuser_Bean.class);

                    if (list.size() == 0) {
                        mPage = -1;
//                        mNoDataView.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        if (mPage == 1) {
                            mListViewAdapter.clear();
                        }
//                        mNoDataView.setVisibility(View.GONE);
                    }
                    if (list != null) {
                        mPage = getNextPage(sr.bodyData.optJSONObject("data").optInt("pagecount"), mPage);
                        mListViewAdapter.addAll(list);
                    }
                }

                resetRefresh();

            }

        };

        if (isFirst) {
            mProgressView.startControl(sc);
        } else {
            sc.startVolley();
        }

    }


    /**
     * 返回下一页的请求页面
     *
     * @param currentPage
     * @return 返回 -1 表示没有下一页了
     */
    public int getNextPage(int totalPages, int currentPage) {

        if (currentPage >= totalPages) {
            return -1;
        } else {
            return currentPage + 1;
        }
    }

    /**
     * 重置刷新状态
     */
    public void resetRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);

        if (mPage < 0) {
            mLoadMoreListView.noMoreData();
        } else {
            mLoadMoreListView.showLoadMore();
        }
    }

    @Override
    public void onLoadMore() {
        if (mPage > 0) {
            requestData(false);
        }
    }

    /*---------------------------------需要重写的方法--------------------*/

    /**
     * 解析 数据
     *
     * @param body
     * @return
     */
    public abstract ArrayList<T> setList(JSONObject body);

    /**
     * 请求 的 Serverc
     *
     * @return
     */
    public abstract ServerControl setServerControl();


    /**
     * 返回listView adapter
     *
     * @return
     */
    public abstract CommonAdapter setAdapter();

}
